﻿using System;
using System.Reflection;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;

namespace Tzx.TUpdater.Utilities
{
    /// <summary>
    /// INI配置文件帮助
    /// </summary>
    internal class IniHelper
    {
        #region API函数声明

        /// <summary>
        /// (返回0失败,非0则成功)
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="val"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        /// <summary>
        /// 返回取得字符串缓冲区长度
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="def"></param>
        /// <param name="retVal"></param>
        /// <param name="size"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal,
                                                           int size, string filePath);

        //private static extern long ReadSections();
        //private static extern long ReadSectionValues();
        //private static extern long ReadSection();

        #endregion

        /// <summary>
        /// 检查Ini文件是否存在,不存在则创建
        /// </summary>
        /// <param name="iniFile"></param>
        private static void CheckCreateIniFile(string iniFile)
        {
            if (!File.Exists(iniFile))
            {
                FileStream fs = File.Create(iniFile);
                //StreamWriter sw = new StreamWriter(fs);
                //sw.WriteLine();
                fs.Close();
            }
        }

        /// <summary>
        /// 默认ini文件路径名称(路径与文件名与当前执行文件相同)
        /// </summary>
        /// <returns></returns>
        internal static string GetDefaultIniFile()
        {
            string dir = string.Format("{0}", AppDomain.CurrentDomain.BaseDirectory);
            string fullFile = string.Format("{0}", Assembly.GetExecutingAssembly().Location);
            string mainFileName = fullFile.Substring(fullFile.LastIndexOf('\\')).Trim('\\');

            //如果是".exe"则使用".ini",如"abc.exe"对应"abc.ini"
            //其它则使用".扩展名.ini",如"abc.dll"对应"abc.dll.ini"
            if (mainFileName.EndsWith(".exe", true, null))
            {
                int index = mainFileName.LastIndexOf(".exe", StringComparison.CurrentCultureIgnoreCase);
                mainFileName = mainFileName.Substring(0, index);
            }

            //对应ini文件
            string iniFile = string.Format("{0}\\{1}.ini", dir.TrimEnd('\\'), mainFileName);
            return iniFile;
        }

        /// <summary>
        /// 读Ini文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="noText"></param>
        /// <param name="iniFilePath"></param>
        /// <returns></returns>
        internal static string ReadIniData(string section, string key, string noText, string iniFilePath)
        {
            if (string.IsNullOrEmpty(iniFilePath))
            {
                return string.Empty;
            }

            CheckCreateIniFile(iniFilePath);

            StringBuilder tmp = new StringBuilder(1024);
            long number = GetPrivateProfileString(section, key, noText, tmp, 1024, iniFilePath);
            //Debug.WriteLine("number=" + number);
            return tmp.ToString();
        }

        /// <summary>
        /// 读Ini文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="noText"></param>
        /// <returns></returns>
        internal static string ReadIniData(string section, string key, string noText)
        {
            string iniFile = GetDefaultIniFile();
            return ReadIniData(section, key, noText, iniFile);
        }

        /// <summary>
        /// 写Ini文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="iniFilePath"></param>
        /// <returns></returns>
        internal static bool WriteIniData(string section, string key, string value, string iniFilePath)
        {
            if (string.IsNullOrEmpty(iniFilePath))
            {
                return false;
            }

            CheckCreateIniFile(iniFilePath);

            long number = WritePrivateProfileString(section, key, value, iniFilePath);
            return number != 0;
        }

        /// <summary>
        /// 写Ini文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        internal static bool WriteIniData(string section, string key, string value)
        {
            string iniFile = GetDefaultIniFile();
            return WriteIniData(section, key, value, iniFile);
        }

    }
}